class ComicRenderer {
    constructor(containerId, baseUrl) {
        this.container = document.getElementById(containerId);
        this.baseUrl = baseUrl;
        this.pages = [];
    }
    
    renderComic(pages) {
        this.pages = pages;
        this.container.innerHTML = '';
        
        console.log('渲染漫画页面:', pages);
        
        if (pages.length === 0) {
            this.showEmptyState();
            return;
        }
        
        // 按场景编号排序
        pages.sort((a, b) => a.scene_number - b.scene_number);
        
        pages.forEach((page, index) => {
            const pageElement = this.createPageElement(page, index);
            this.container.appendChild(pageElement);
        });
    }
    
    createPageElement(page, index) {
        const pageDiv = document.createElement('div');
        pageDiv.className = 'comic-page';
        pageDiv.id = `page-${page.page_id}`;
        
        // 页面头部
        const headerDiv = document.createElement('div');
        headerDiv.className = 'page-header';
        
        const titleSpan = document.createElement('span');
        titleSpan.className = 'page-title';
        titleSpan.textContent = `第 ${page.scene_number} 页`;
        
        const actionsDiv = document.createElement('div');
        actionsDiv.className = 'page-actions';
        
        const downloadBtn = document.createElement('button');
        downloadBtn.className = 'btn-secondary';
        downloadBtn.textContent = '下载本页';
        downloadBtn.onclick = () => this.downloadPage(page.page_id);
        
        actionsDiv.appendChild(downloadBtn);
        headerDiv.appendChild(titleSpan);
        headerDiv.appendChild(actionsDiv);
        
        // 面板容器
        const panelsContainer = document.createElement('div');
        panelsContainer.className = 'panels-container';
        
        // 添加面板
        page.panels.forEach((panel, panelIndex) => {
            const panelElement = this.createPanelElement(panel, panelIndex, page);
            panelsContainer.appendChild(panelElement);
        });
        
        pageDiv.appendChild(headerDiv);
        pageDiv.appendChild(panelsContainer);
        
        return pageDiv;
    }
    
    createPanelElement(panel, index, page) {
        const panelDiv = document.createElement('div');
        panelDiv.className = 'comic-panel';
        
        const imgContainer = document.createElement('div');
        imgContainer.className = 'panel-image-container';
        
        const img = document.createElement('img');
        img.className = 'panel-image';
        img.alt = `第 ${page.scene_number} 页 - 场景 ${index + 1}`;
        img.loading = 'lazy';
        img.style.opacity = '0';
        img.style.transition = 'opacity 0.3s ease';
        
        // 设置图片源
        this.loadPanelImage(panel.image_path, img, page.scene_number);
        
        imgContainer.appendChild(img);
        
        // 如果有对话，添加对话气泡
        if (panel.dialogue && panel.dialogue.trim() && panel.dialogue !== '示例对话') {
            const dialogueDiv = document.createElement('div');
            dialogueDiv.className = 'panel-dialogue';
            dialogueDiv.innerHTML = `
                <div class="dialogue-bubble">
                    <div class="dialogue-text">${panel.dialogue}</div>
                </div>
            `;
            panelDiv.appendChild(dialogueDiv);
        }
        
        panelDiv.appendChild(imgContainer);
        return panelDiv;
    }
    
    async loadPanelImage(imagePath, imgElement, sceneNumber) {
        try {
            // 构建完整的图片URL
            const imageUrl = `${this.baseUrl}/api/get-comic-page/${imagePath}`;
            console.log(`加载场景 ${sceneNumber} 的图片:`, imageUrl);
            
            // 添加时间戳避免缓存
            const timestamp = new Date().getTime();
            const urlWithTimestamp = `${imageUrl}?t=${timestamp}`;
            
            imgElement.src = urlWithTimestamp;
            
            imgElement.onload = () => {
                console.log(`场景 ${sceneNumber} 图片加载成功`);
                imgElement.style.opacity = '1';
            };
            
            imgElement.onerror = (e) => {
                console.error(`场景 ${sceneNumber} 图片加载失败:`, imageUrl, e);
                
                // 显示错误占位图
                imgElement.src = this.getErrorImage(sceneNumber);
                imgElement.style.opacity = '1';
                imgElement.style.border = '2px dashed red';
                
                // 显示错误信息
                const errorDiv = document.createElement('div');
                errorDiv.className = 'image-error';
                errorDiv.innerHTML = `
                    <div style="text-align: center; padding: 20px; color: #d32f2f;">
                        <div>❌ 图片加载失败</div>
                        <div style="font-size: 12px; margin-top: 5px;">
                            场景 ${sceneNumber} - ${imagePath}
                        </div>
                        <button onclick="retryLoadImage('${imagePath}', ${sceneNumber})" 
                                style="margin-top: 10px; padding: 5px 10px; background: #d32f2f; color: white; border: none; border-radius: 3px; cursor: pointer;">
                            重试加载
                        </button>
                    </div>
                `;
                imgElement.parentNode.appendChild(errorDiv);
            };
            
        } catch (error) {
            console.error('加载漫画图片错误:', error);
            imgElement.src = this.getErrorImage(sceneNumber);
            imgElement.style.opacity = '1';
        }
    }
    
    getErrorImage(sceneNumber) {
        // 创建错误提示图片
        return 'data:image/svg+xml;base64,' + btoa(`
            <svg width="800" height="600" xmlns="http://www.w3.org/2000/svg">
                <rect width="100%" height="100%" fill="#ffebee"/>
                <text x="50%" y="45%" text-anchor="middle" font-family="Arial" font-size="20" fill="#d32f2f">
                    🚫 图片加载失败
                </text>
                <text x="50%" y="55%" text-anchor="middle" font-family="Arial" font-size="14" fill="#d32f2f">
                    场景 ${sceneNumber}
                </text>
            </svg>
        `);
    }
    
    getPlaceholderImage() {
        // 创建加载中占位图片
        return 'data:image/svg+xml;base64,' + btoa(`
            <svg width="800" height="600" xmlns="http://www.w3.org/2000/svg">
                <rect width="100%" height="100%" fill="#f5f5f5"/>
                <text x="50%" y="50%" text-anchor="middle" dy=".3em" font-family="Arial" font-size="20" fill="#666">
                    ⏳ 图片加载中...
                </text>
            </svg>
        `);
    }
    
    showEmptyState() {
        this.container.innerHTML = `
            <div class="empty-state">
                <div style="text-align: center; padding: 60px 20px; color: #6c757d;">
                    <div style="font-size: 4rem; margin-bottom: 20px;">🎨</div>
                    <h3>尚未生成漫画</h3>
                    <p>请在上方输入小说文本并点击生成按钮</p>
                </div>
            </div>
        `;
    }
    
    async downloadPage(pageId) {
        try {
            console.log('开始下载页面:', pageId);
            
            const response = await fetch(`${this.baseUrl}/api/get-comic-page/${pageId}`);
            
            if (response.ok) {
                const blob = await response.blob();
                
                if (blob.size === 0) {
                    throw new Error('下载的文件为空');
                }
                
                // 创建下载链接
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `漫画页面-${pageId}.png`;
                
                // 触发下载
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                
                // 清理URL
                setTimeout(() => URL.revokeObjectURL(url), 100);
                
                console.log('下载成功:', pageId);
            } else {
                let errorMessage = `下载失败: ${response.status}`;
                try {
                    const errorData = await response.json();
                    errorMessage = errorData.error || errorMessage;
                } catch (e) {
                    // 忽略JSON解析错误
                }
                throw new Error(errorMessage);
            }
        } catch (error) {
            console.error('下载页面错误:', error);
            alert('下载失败: ' + error.message);
        }
    }
    
    async downloadAllPages() {
        if (this.pages.length === 0) {
            alert('没有可下载的页面');
            return;
        }
        
        const results = [];
        for (const page of this.pages) {
            try {
                await this.downloadPage(page.page_id);
                results.push({ page: page.scene_number, status: '成功' });
                // 添加延迟避免请求过于频繁
                await new Promise(resolve => setTimeout(resolve, 1000));
            } catch (error) {
                results.push({ page: page.scene_number, status: '失败', error: error.message });
            }
        }
        
        // 显示下载结果摘要
        const successCount = results.filter(r => r.status === '成功').length;
        const failCount = results.filter(r => r.status === '失败').length;
        
        if (failCount > 0) {
            alert(`下载完成:\n成功: ${successCount} 个文件\n失败: ${failCount} 个文件`);
        } else {
            alert(`下载完成: 所有 ${successCount} 个文件下载成功`);
        }
    }
}

// 全局重试函数
window.retryLoadImage = function(imagePath, sceneNumber) {
    console.log(`重试加载场景 ${sceneNumber} 的图片`);
    const images = document.querySelectorAll(`img[alt*="场景 ${sceneNumber}"]`);
    images.forEach(img => {
        const timestamp = new Date().getTime();
        img.src = `http://localhost:5000/api/get-comic-page/${imagePath}?t=${timestamp}`;
        
        // 移除错误信息
        const errorDiv = img.parentNode.querySelector('.image-error');
        if (errorDiv) {
            errorDiv.remove();
        }
    });
};